package com.epam;

import java.util.Arrays;
import java.util.RandomAccess;

public class MyArrayList implements MyList, RandomAccess {

	private Object[] data;
	private int length;

	public MyArrayList(int size) {
		data = new Object[size];
		length = data.length;
	}

	private void ensureCapacity(int capacity) {
		if (capacity > length) 
			data = Arrays.copyOf(data, capacity);
	}

	private void checkIndex(int index) {
		if (index > length || index < 0) throw new RuntimeException("wrong index");
	}

	@Override
	public void add(Object e) {
		ensureCapacity(length + 1);
		data[length++] = e;
	}

	@Override
	public void add(int index, Object element) {
		checkIndex(index);

		ensureCapacity(length + 1);
		System.arraycopy(data, index, data, index + 1,
				length - index);
		data[index] = element;
		length++;
	}

	@Override
	public void addAll(Object[] c) {
		ensureCapacity(length + c.length);
		System.arraycopy(c, 0, data, length, c.length);
		length += c.length;
	}

	@Override
	public void addAll(int index, Object[] c) {
		checkIndex(index);

		ensureCapacity(length + c.length);

		System.arraycopy(data, index, data, c.length + index, length - index);
		System.arraycopy(c, 0, data, index,	c.length);
		length += c.length ;
	}

	@Override
	public Object get(int index) {
		checkIndex(index);
		return data[index];
	}

	@Override
	public Object remove(int index) {
		checkIndex(index);
		Object o = get(index);
		System.arraycopy(data, index+1, data, index, length - index - 1);
		data = Arrays.copyOfRange(data, 0, data.length - 1);
		length--;
		return o;
	}

	@Override
	public void set(int index, Object element) {
		data[index] = element;
	}

	@Override
	public int indexOf(Object o) throws NullPointerException{

		for (int i = 0; i < length; i++) {
			if (o.equals(data[i]))
				return i;
		}
		return -1;
	}

	@Override
	public int size() {
		return length;
	}

	@Override
	public Object[] toArray() {
		return Arrays.copyOf(data, length);
	}

	@Override
	public String toString() {
		return Arrays.toString(data);
	}

}
